layui.use(['layer', 'form','ax', 'table', 'treetable'], function () {
    var form = layui.form;
    var $ax = layui.ax;
    var table = layui.table;
    var treetable = layui.treetable;

    /**
     * 系统管理--菜单管理
     */
    var Current = {
        tableId: "table"
    };

    /**
     * 比对arg值并选址0 和1 对应值
     * @param arg
     * @param v0
     * @param v1
     * @returns {string|*}
     */
    function chooseResult(arg,v0 ,v1){
        if(arg === 0){
            return v0;
        }
        if(arg === 1){
            return v1;
        }
        return "";
    }

    /**
     * 初始化表格的列
     */
    Current.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, sort: true, title: 'id'},
            {field: 'name', sort: true, title: '方法名',width:300},
            {field: 'args', sort: true, title: '参数'},
            {field: 'uriMethod', sort: true, title: '请求类型',width:60},
            {field: 'uri', sort: true, title: '请求地址'},
            {field: 'fullUri', sort: true, title: '完整地址'},
            {field: 'resultType', sort: true, title: '返回内容',width:60 ,templet: function (d) {
                    return chooseResult(d.resultType ,"html" ,"json");
                }
            },
            {field: 'permissionSymbol', sort: true, title: '是否认证' ,toolbar: '#permissionSymbolTpl' ,width:100},
            {field: 'status', sort: true, title: '状态' ,toolbar: '#statusTpl',width:100},
            {field: 'pid', hide: true, sort: true, title: 'pid'}
        ]];
    };

    /**
     * 初始化表格
     */
    Current.initTable = function (tableId, data) {
        return treetable.render({
            elem: '#' + tableId,
            url: system.contextPath + '/develop/function/search/tree/table',
            where: data,
            page: false,
            height: "full-158",
            cellMinWidth: 100,
            cols: Current.initColumn(),
            treeColIndex: 2,
            treeSpid: "0",
            treeIdName: "id",
            treePidName: "pid",
            treeDefaultClose: true,
            treeLinkage: false
            ,isJump: true //是否允许点击节点时弹出新窗口跳转
            ,showLine: true,  //是否开启连接线
            size: 'lg',
            done: function (res, curr, count) {
                count || this.elem.next('.layui-table-view').find('.layui-table-header').css('overflow', 'visible');
            $('.layui-table-body').find('div.layui-table-cell').find('select').each(function () {
                var $this = $(this);
                var val = $this.data('value');
                var text;
                $(this).children().each(function () {
                    if (val == this.value) {
                        text = this.text;
                        return;
                    }
                })
                //更新layui 选择器输入框的值
                $this.next().find('.layui-select-title').find('input').val(text);
                //更新layui 选择器的值 以及设置其样式
                $this.val(val).parents('div.layui-table-cell').css('overflow', 'visible');
            })
            form.render(null, 'table');
            }
        });
    };

    // 渲染表格
    var tableResult = Current.initTable(Current.tableId);

    $('#expandAll').click(function () {
        treetable.expandAll('#' + Current.tableId);
    });

    $('#foldAll').click(function () {
        treetable.foldAll('#' + Current.tableId);
    });

    /**
     * 表格选中事件
     */
    table.on('checkbox(table)', function(obj){
        //全部选择不必更新
        if(obj.type == "one"){
            //更新子节点选中状态
            updateTableCheckStatus($(obj.tr).nextAll() ,obj.data.id ,obj.checked);
        }
    });

    //选中id 变量
    var checkedIds = [];
    function updateTableCheckStatus($all ,pid ,isChecked){
        if(isChecked){
            checkedIds.push(pid);
        }else{
            checkedIds = checkedIds.filter(function (value) { return value != pid });
        }

        $all.each(function () {
            var $nextTr = $(this);
            var $nextChildren = $nextTr.children();
            var nextPid = $nextChildren.eq($nextChildren.length -1).children().eq(0).text();
            if(nextPid == pid){
                var $checkedContainer = $nextTr.find("div.layui-unselect.layui-form-checkbox");
                if(isChecked){
                    $checkedContainer.addClass("layui-form-checked");
                    var $nextCheckbox = $nextTr.find("input[type='checkbox']");
                    $nextCheckbox.attr("checked","checked");
                    $nextCheckbox.prop("checked",true);
                }else{
                    $checkedContainer.removeClass("layui-form-checked");
                    var $nextCheckbox = $nextTr.find("input[type='checkbox']");
                    $nextCheckbox.attr("checked","");
                    $nextCheckbox.prop("checked",false);
                }

                //更新子节点
                var nextNodePid = $nextChildren.eq(1).children().eq(0).text();
                updateTableCheckStatus($all , nextNodePid,isChecked);
            }

        });
    }

    // 监听修改update到表格中
    form.on('select(permissionSymbolFilter)', function (data) {
        var id = $(data.elem).attr("data-id");
        var data = buildUpdateData(id ,"permissionSymbol" ,data.value);
        updateBatchById(data);

        reloadTableAndLocation(id);
    });

    // 监听修改update到表格中
    form.on('select(statusFilter)', function (data) {
        var id = $(data.elem).attr("data-id");
        var data = buildUpdateData(id ,"status" ,data.value);
        updateBatchById(data);

        reloadTableAndLocation(id);
    });

    function buildUpdateData(currentId ,filed ,filedValue){
        var ids = "";
        if(checkedIds.length == 0){
            //没有选中，只更新当前值
            ids = currentId;
        }else{
            // 有选中项目，更新选中项目
            checkedIds.forEach(function (value, index, array) {
                ids += value + ",";
            });
        }
        var data = {'ids': ids};
        data[filed] = filedValue;
        return data;
    }

    function updateBatchById(data){
        var ajax = new $ax(system.contextPath + "/develop/function/update/batch/ids", function(res) {
            if(res.code == 200){
                system.success("修改成功！");
                //重新加载表格
                Current.initTable(Current.tableId)
                checkedIds =[];
            }else{
                system.error("失败：" + res.msg);
            }
        }, function(res) {
            system.error("失败：" + res.msg);
        });
        ajax.set(data);
        ajax.start();
    }

    function reloadTableAndLocation(id){
        //记录表格位置
        var scrollTop=0;
        var layuiTable = $('.layui-table-main');

        if(layuiTable!=null&&layuiTable.length>0){
            scrollTop = layuiTable[0].scrollTop;
        }

        //重载表格
        Current.initTable(Current.tableId);

        //这里必须使用setTimeout ，跳转记录位置
        setTimeout(function(){
            //打开树节点
            var targetArray = new Array();
            var inId = id;
            while( inId && inId != 0){
                var $target = $($.find("[lay-tid="+inId+"]"));
                inId = $target.attr("lay-tpid");
                targetArray.push($target);
            }

            for(var i = targetArray.length -1 ;i >=0 ;--i){
                targetArray[i].click();
            }

            //跳转位置
            if(layuiTable!=null&&layuiTable.length>0){
                $('.layui-table-main').scrollTop(scrollTop)
            }
        },300)
    }
});
